import React from "react"
import { View, Text, ViewStyle, TouchableOpacity, TextStyle } from "react-native"
import { withRouter } from "react-router-dom"
import { isWeb } from "../../utils"

const headerStyle: ViewStyle = {
  backgroundColor: "#fff",
  alignItems: "center",
  flexDirection: "row",
  borderTopWidth: 1,
  borderTopColor: "#ececec"
}

class NavBtn extends React.Component<any, any> {
  state = {
    active: false
  }

  navBtnWrapStyle: ViewStyle = {
    flex: 1,
    alignItems: "center",
    flexDirection: "row",
    justifyContent: "center"
  }

  onPress = () => {
    const props: any = this.props
    console.log("props", props)
    if (isWeb) {
      props.history.push(`/${props.to}`)
    } else {
      props.navigation.replace({
        routeName: props.to
      })
    }
    if (props.setActive) {
      props.setActive(props.to)
    }
  }

  navBtnStyle: ViewStyle = {
    flex: 1,
    height: 60,
    backgroundColor: "#fafafa",
    justifyContent: "center",
    alignItems: "center"
  }

  navBtnActiveStyle: ViewStyle = {
    backgroundColor: "#398bff"
  }

  navBtnTextStyle: TextStyle = {
    color: "#000",
    fontSize: 16
  }

  navBtnTextActiveStyle: TextStyle = {
    color: "#fff"
  }

  render() {
    const { children, matchRoute, to }: any = this.props
    const mergeNavBtnStyle: ViewStyle = {
      ...this.navBtnStyle,
      ...(matchRoute === to ? this.navBtnActiveStyle : {})
    }

    const mergeNavBtnTextStyle: TextStyle = {
      ...this.navBtnTextStyle,
      ...(matchRoute === to ? this.navBtnTextActiveStyle : {})
    }

    return (
      <TouchableOpacity style={this.navBtnWrapStyle} onPress={this.onPress}>
        <View style={mergeNavBtnStyle}>
          <Text style={mergeNavBtnTextStyle}>{children}</Text>
        </View>
      </TouchableOpacity>
    )
  }
}

class TabNavigator extends React.Component<any> {
  state = {
    matchRoute: "betRecord"
  }

  setNavBtnActive = (router: string) => {
    console.log("setNavBtnActive", router)
    this.setState({
      matchRoute: router
    })
  }

  render() {
    console.log("render", this.props)

    const { routes } = this.props

    return (
      <View style={headerStyle}>
        {routes.map(router => {
          return (
            <NavBtn
              key={router.path}
              {...this.props}
              matchRoute={this.state.matchRoute}
              to={router.path}
              setActive={this.setNavBtnActive}
            >
              {router.name}
            </NavBtn>
          )
        })}
      </View>
    )
  }
}

export const BottomTabNavigation = isWeb ? withRouter(TabNavigator) : TabNavigator

// export default withRouter(TabNavigator)
